
package com.oraking.android.hybridapp.dev.korealaw.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;

import com.oraking.android.hybridapp.dev.korealaw.R;
import com.oraking.android.hybridapp.dev.korealaw.holder.ParamHolder;
import com.oraking.android.hybridapp.dev.korealaw.util.CmmStr;
import com.phonegap.DroidGap;

/**
 * 파일명          : KoreaLawCn.java 
 * 작성일          : 2011. 10. 4.
 * 작성자          : <a href='http://oraking.springnote.com/' target='_blank'>Teddy</a>
 * Todo      :
 * 수정내용
 * -------------------------------------------------------------
 *      수정일      |      수정자      |              수정내용              
 * -------------------------------------------------------------
 *              |              |
 */

public class KoreaLawCn extends DroidGap{
	
	Context mContext;
	
	WebView webView;
	Button mButton;
	ProgressDialog dial;	// ProgressBar
	
	
	String filePath;		// filePath 얻기
	
	// Handler 관련 상수 Start
	static final int PROGRESS_START = 0;
	static final int PROGRESS_STOP = 1;
	static final int HTML_GET = 2;
	static final int ACTIVITY_SWITCH = 3;
	static final int ERROR_MESSAGE = 4;
	// Handler 관련 상수 End
	
	@Override
	public void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		getResource();							// Resource 가져오기
		configueScreen();						// 화면 구성하기
		mHandler.sendEmptyMessage(HTML_GET);	// 데이터 요청하기
	}
	
	// Data Communication 관련 Handler
	final Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case PROGRESS_START:
				dial.show();
				break;
			case PROGRESS_STOP:
				dial.dismiss();
				break;
			case HTML_GET:
				getSavedHTML();
				break;
			case ACTIVITY_SWITCH:
				switchActivity((ParamHolder)msg.obj);
				break;
			case ERROR_MESSAGE:
				Message toastMessage = Message.obtain();
				toastMessage.obj = msg.obj;
				toastHandler.sendMessage(toastMessage);
				break;
			default:
				break;
			}
		}
		
	};
	
	Handler toastHandler = new Handler(){
		boolean isShow = false;
		public void handleMessage(Message msg) {
			
			if(!isShow){
				isShow = true;
				Toast.makeText(KoreaLawCn.this, String.valueOf(msg.obj), Toast.LENGTH_SHORT).show();
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						try {
							Thread.sleep(2000);
							isShow = false;
						} catch (InterruptedException e) {
						}
					}
				}).start();
			}
			
		};
	};
	
	/**
	 * @title  : 
	 * @location : com.oraking.android.hybridapp.dev.korealaw.activity.KoreaLawCn.configueScreen
	 * @writeDay : 2011. 10. 4. 오전 10:11:18
	 * @Todo  : TODO
	 */
	private void configueScreen() {
		// TODO Auto-generated method stub
		setContentView(R.layout.korealawcn);
		webView = (WebView) findViewById(R.id.webview);
		mButton = (Button) findViewById(R.id.btnsearch);
		        
		// WebView Setting Start
		webView.setWebViewClient(new ProxyWebViewClient());						// WebViewClient 지정
		webView.addJavascriptInterface(new AdroidBridge(), "HybridApp");		// Bridge 인스턴스 등록
		webView.getSettings().setJavaScriptEnabled(true);						// Javascript 사용시 설정
		webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		webView.getSettings().setAllowFileAccess(true);
		webView.getSettings().setLightTouchEnabled(true);
		webView.getSettings().setBuiltInZoomControls(false);
		webView.setHorizontalScrollBarEnabled(false);
		webView.setVerticalScrollbarOverlay(true);								// 웹뷰 오른쪽 스크롤바 공간 없애기 설정
		// WebView Setting End
		
		
		mButton.setOnClickListener( new OnClickListener(){
			public void onClick(View view) {
				//Log.d("debug", "click!");
				webView.loadUrl("javascript:setMessage('12')");			
			}
	     });
	}
	
	// 리소스 구성 관련 Method
	private void getResource(){
		mContext = getApplicationContext();						// Content 객체 얻기
        filePath = mContext.getFilesDir().getPath()+"/";		// filePath 얻기

     // ProgressDialog 리소스 얻기 Start
		dial = new ProgressDialog(KoreaLawCn.this);
        dial.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dial.setMessage("Wait a monent...");
        // ProgressDialog 리소스 얻기 End
	}
	
	// 저장된 HTML 가져오는 Mehtod
	private void getSavedHTML(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				mHandler.sendEmptyMessage(PROGRESS_START);
								
				webView.loadUrl("file:///android_asset/www/KoreaLawCn.html");
				
			}
		}).start();
	}

	private void switchActivity(ParamHolder paramHolder){
		Intent mIntent = new Intent(KoreaLawCn.this, KoreaLawList.class);
		mIntent.putExtra("paramHolder", paramHolder);
		startActivity(mIntent);
	}
	
	private class AdroidBridge{
		@SuppressWarnings("unused")
		public void setMessage(final String str){
			new Thread(new Runnable() {
				@Override
				public void run() {
					Log.d("debug", "HybridApp : " + str);
					
					// Message 에 검색조건 담기
					Message msg = Message.obtain();
					
					// Parameter Parse Start
					String [] params = str.split("&");
					String keyword = "";
					String selectChoice = "";
					
					for(String param : params){
						if(param != null && param.length() != 0){
							if(param.startsWith("keyword=")){
								keyword=param.substring(param.indexOf("=")+1);
							}
							else if(param.startsWith("select-choice-a=")){
								selectChoice=param.substring(param.indexOf("=")+1);
							}
						}
					}					
					// Parameter Parse End
					
					// 법 관련 상수가 선택하지 않았을 경우
					if("".equals(selectChoice)){
						msg.what = ERROR_MESSAGE;
						msg.obj = CmmStr.ERROR_MESSAGE_3;
					}
					// 법령조회 관련 서비스가 준비되지 않았을 경우
					else if(selectChoice.equals(CmmStr.ADMRUL) || selectChoice.equals(CmmStr.ORDIN) || selectChoice.equals(CmmStr.TRTY) || selectChoice.equals(CmmStr.PREC) || selectChoice.equals(CmmStr.LICBYL) || selectChoice.equals(CmmStr.LSTRM)){
						msg.what = ERROR_MESSAGE;
						msg.obj = CmmStr.ERROR_MESSAGE_4;
					// 법령조회 서비스가 준비된 경우
					}else if(selectChoice.equals(CmmStr.LAW)){
						ParamHolder paramHolder = new ParamHolder();
						paramHolder.keyword = keyword;
						paramHolder.selectChoice = selectChoice;
						
						msg.obj = paramHolder;
						msg.what = ACTIVITY_SWITCH;
					// 법령조회 관련 서비스가 준비되지 않았을 경우
					}else{
						msg.what = ERROR_MESSAGE;
						msg.obj = CmmStr.ERROR_MESSAGE_4;
					}
					
					mHandler.sendMessage(msg);
				}
			}).start();
		}
	}
	
	
	private class ProxyWebViewClient extends WebViewClient {

		@Override
		public void onPageFinished(WebView view, String url) {
			// TODO Auto-generated method stub
			mHandler.sendEmptyMessage(PROGRESS_STOP);
			super.onPageFinished(view, url);
		}
		
		@Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
		
	}
}
